<template>
  <CommonModal
    :visible="workflowStore.isParamConfigVisible"
    :title="modalTitle"
    width="500px"
    @close="workflowStore.closeParamConfig()"
    @confirm="saveParams"
  >
    <el-form :model="params" label-width="120px" ref="paramForm">
      <div v-if="configFields.length > 0">
        <div v-for="field in configFields" :key="field.key" class="form-field">
          <el-form-item :label="field.label" :prop="field.key">
            <!-- 单选框 -->
            <el-radio-group 
              v-if="field.type === 'radio'" 
              v-model="params[field.key]"
            >
              <el-radio 
                v-for="option in field.options" 
                :key="option.value" 
                :label="option.value"
              >
                {{ option.label }}
              </el-radio>
            </el-radio-group>
            
            <!-- 下拉选择框 -->
            <el-select 
              v-else-if="field.type === 'select'" 
              v-model="params[field.key]" 
              style="width: 100%"
            >
              <el-option 
                v-for="option in field.options" 
                :key="option.value" 
                :label="option.label"
                :value="option.value"
              />
            </el-select>
            
            <!-- 复选框 -->
            <el-checkbox-group 
              v-else-if="field.type === 'checkbox'" 
              v-model="params[field.key]"
            >
              <el-checkbox 
                v-for="option in field.options" 
                :key="option.value" 
                :label="option.value"
              >
                {{ option.label }}
              </el-checkbox>
            </el-checkbox-group>
            
            <!-- 输入框 -->
            <el-input 
              v-else-if="field.type === 'input'" 
              v-model="params[field.key]" 
              :placeholder="field.placeholder"
            />
            
            <!-- 参数描述 -->
            <div 
              v-if="field.descriptions && params[field.key]" 
              class="param-description"
            >
              {{ field.descriptions[params[field.key]] }}
            </div>
          </el-form-item>
        </div>
      </div>
      <el-empty v-else description="该节点无需配置参数" />
    </el-form>
  </CommonModal>
</template>

<script setup>
import { ref, watch, computed } from 'vue';
import { useWorkflowStore } from '../../stores/workflow';
import { storeToRefs } from 'pinia';
import CommonModal from '../common/CommonModal.vue';

const workflowStore = useWorkflowStore();
const { currentNode } = storeToRefs(workflowStore);
const params = ref({});
const paramForm = ref(null);

// 使用计算属性确保标题的响应式更新
const modalTitle = computed(() => {
  return currentNode.value ? `${currentNode.value.text} 参数配置` : '参数配置';
});

// 监听当前节点变化，更新表单
watch(() => workflowStore.currentNode, (node) => {
  if (node) {
    // 深拷贝节点参数，避免直接修改store中的状态
    params.value = JSON.parse(JSON.stringify(node.params || {}));
    // 初始化默认值
    initializeDefaultParams();
  } else {
    // 节点为空时，清空表单
    params.value = {};
  }
}, { deep: true, immediate: true });

// 根据节点类型动态生成配置项
const configFields = computed(() => {
  const node = currentNode.value;
  
  if (!node) return [];
  let fields = [];
  // 根据节点类型和名称来决定显示哪些配置项
  switch (node.type) {
    case 'input':
      if (node.text === '文件选择') {
        fields = [
          { key: 'fileName', label: '文件名', type: 'input', placeholder: '请输入文件名' },
          { key: 'fileType', label: '文件类型', type: 'select', options: [{label: 'CSV', value: 'csv'}, {label: 'Excel', value: 'excel'}, {label: 'JSON', value: 'json'}], defaultValue: 'csv' }
        ];
      }
      break;
      
    case 'process':
      if (node.text === '数据预处理') {
        fields = [
          { key: 'imputation', label: '缺失值填充', type: 'radio', options: [{label: '均值填充', value: 'mean'}, {label: '中位数填充', value: 'median'}, {label: '删除样本', value: 'delete'}], defaultValue: 'mean', descriptions: {'mean': '用特征均值填充', 'median': '用特征中位数填充', 'delete': '删除任何含缺失值的行'} },
          { key: 'normalization', label: '标准化方式', type: 'radio', options: [{label: '0-1归一化', value: 'min-max'}, {label: 'log2标准化', value: 'log2'}, {label: '不处理', value: 'none'}], defaultValue: 'min-max' },
        ];
      }
      if (node.text === '降维分析') {
        fields = [
          { key: 'algorithm', label: '降维算法', type: 'select', options: [{label: 'PCA', value: 'pca'}, {label: 't-SNE', value: 'tsne'}, {label: 'UMAP', value: 'umap'}], defaultValue: 'pca' },
          { key: 'dims', label: '目标维度', type: 'input', placeholder: '请输入1-3的整数', rules: [{ required: true, message: '目标维度不能为空'}, { pattern: /^[1-3]$/, message: '请输入1-3的整数' }] },
        ];
      }
      if (node.text === '模型校准') {
        fields = [
          { key: 'model', label: '校准模型', type: 'select', options: [{label: '逻辑回归', value: 'lr'}, {label: 'SVM', value: 'svm'}, {label: '随机森林', value: 'rf'}], defaultValue: 'lr' },
          { key: 'threshold', label: '置信度阈值', type: 'input', placeholder: '请输入0-1的小数', rules: [{ required: true, message: '阈值不能为空'}, { pattern: /^(0(\.\d+)?|1(\.0+)?)$/, message: '请输入0-1之间的小数' }] },
        ];
      }
      break; 
      
    case 'output':
      if (node.text === '结果预览') {
        fields = [
          { key: 'format', label: '展示格式', type: 'select', options: [{label: '表格', value: 'table'}, {label: '图表', value: 'chart'}], defaultValue: 'table' },
          { key: 'limit', label: '显示条数', type: 'input', placeholder: '请输入显示条数', defaultValue: '100' }
        ];
      }
      if (node.text === '文件导出') {
        fields = [
          { key: 'format', label: '导出格式', type: 'select', options: [{label: 'CSV', value: 'csv'}, {label: 'Parquet', value: 'parquet'}, {label: 'PDF', value: 'pdf'}], defaultValue: 'csv' },
          { key: 'content', label: '导出内容', type: 'checkbox', options: [{label: '原始数据', value: 'raw'}, {label: '处理后数据', value: 'processed'}, {label: '可视化图表', value: 'charts'}], defaultValue: ['processed', 'charts'] },
        ];
      }
      break;
      
    default:
      fields = [];
  }

  console.log('configFields value', fields );
  return fields;
  
});

// 将默认值初始化逻辑提取为独立函数
const initializeDefaultParams = () => {
  if (!currentNode.value || !configFields.value) return;
  
  let changed = false;
  configFields.value.forEach(field => {
    if (params.value[field.key] === undefined && field.defaultValue !== undefined) {
      params.value[field.key] = field.defaultValue;
      changed = true;
    }
  });

  if (changed) {
    // 确保响应式更新
    params.value = { ...params.value };
  }
};

const saveParams = async () => {
  if (!paramForm.value) {
    workflowStore.saveNodeParams(params.value);
    return;
  }
  try {
    await paramForm.value.validate();
    workflowStore.saveNodeParams(params.value);
  } catch (error) {
    console.log('表单验证失败', error);
  }
};
</script>

<style scoped>
.param-description {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 5px;
}
.form-field {
  margin-bottom: 15px;
}
</style>